<template>
  <view class="setting oh">
    <scroll-view class="whf" scroll-y>
      <view class="content wf y">
        <view class="line xcc">
          <button class="avatar xcc" open-type="chooseAvatar" @chooseavatar="chooseavatar">
            <image v-if="!!tmpAtar" :src="tmpAtar" mode="aspectFill" fade-show class="whf" />
            <view v-else class="mac-ico-customer" />
          </button>
        </view>
        <view class="line">
          <view class="label">昵称:</view>
          <input v-model="name" />
        </view>
        <view class="line">
          <view class="label">用户名:</view>
          <input v-model="username" />
        </view>
        <view class="line">
          <view class="label">密码:</view>
          <input v-model="password" placeholder="如不修改,请留空" password />
        </view>
        <view class="line" v-if="!!password">
          <view class="label"><text style="color:red">*</text>确认密码:</view>
          <input v-model="repassword" placeholder="请重新输入密码" password />
        </view>
        <view class="line" @click="goAddr">
          <view class="label">收货地址</view>
          <view class="x jc wf input">
            <input :value="addr" placeholder="请点击添加收货地址" disabled class="fg1" />
            <view class="ml1em mac-ico-d-r" />
          </view>
        </view>
        <view class="bottom xcc">
          <view class="confirm" @click="saveData()">确认修改</view>
          <view class="switch-user" @click="reLogin()">切换用户</view>
        </view>
      </view>
    </scroll-view>
    <Dialog title="重新登录" ref="dig">
      <view class="line">
        <view class="label">用户名:</view>
        <input v-model="formData.username" placeholder="请输入用户名" />
      </view>
      <view class="line">
        <view class="label">密码:</view>
        <input v-model="formData.password" placeholder="请输入密码" password />
      </view>
      <view class="line line-select">
        <view class="label">保留当前登录账户:</view>
        <switch :checked="!formData.del" @change="changeDel" style="transform:scale(0.7)" />
      </view>
    </Dialog>
  </view>
</template>
<script lang="ts">
  import { defineComponent } from "vue";
  import { upload, strParse, apiUrl, api, next, formatUrl } from "@/util";
  import Dialog from "@/components/Dialog.vue";
  export default defineComponent({
    name: "setting",
    components: { Dialog },
    watch: {
      me: {
        handler(n) {
          this.name = n.name;
          this.tmpAtar = n.other.avatar;
          this.username = n.username;
        }, immediate: true,
      }
    },
    data() {
      return {
        me: api.me,
        tmpAtar: "",
        name: "",
        password: "",
        repassword: "",
        username: "",
        addr: "",
        formData: {
          username: "",
          password: "",
          del: true,
        }
      };
    },
    onLoad() {
      this.init();
    },
    methods: {
      async init() {
        while (!(api.me && api.me.id)) {
          await next();
        }
        this.me = api.me;
        await gd.addr.read();
        gd.addr.sort((a, b) => b.createTime - a.createTime);
        const def = (gd.addr.find(e => e.def) || gd.addr[0]);
        this.addr = def ? `${def.name}:${def.phone} ${def.addr}` : "";
      },
      chooseavatar(p: any) {
        this.tmpAtar = p.detail.avatarUrl;
        this.saveData();
      },
      getUpData() {
        const r: obj = {};
        if (this.name !== this.me.name) { r.name = this.name; }
        if (this.password) {
          if (this.password === this.repassword) {
            r.password = this.password;
          } else {
            msg({ title: "请重新确认密码", icon: "error" });
            return;
          }
        }
        if (this.username && this.username !== this.me.username) { r.username = this.username; }
        if (Object.keys(r).length) {
          return r;
        }
      },
      saveData() {
        const obj = this.getUpData();
        if (this.tmpAtar && this.tmpAtar !== this.me.other.avatar) {
          upload({
            filePath: this.tmpAtar,
            name: "pic",
            header: { token: api.token },
            formData: { type: "avatar" },
            success: (res) => {
              const r = strParse(res.data, { url: "" });
              if (r.url) {
                this.changeUser(Object.assign(this.getUpData() || {}, {
                  id: this.me.id,
                  other: Object.assign(this.me.other, { avatar: formatUrl(r.url, apiUrl) })
                }));
              }
            }, fail(e) {
              console.log("错误", e);
            }
          });
        } else if (obj) {
          this.changeUser(Object.assign({ id: api.mid }, obj));
        }
      },
      async changeUser(p: any) {
        if (await api.request(p, "userUpdate")) {
          Object.assign(api.me, p);
          msg({ title: "修改成功" });
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        }
      },
      goAddr() {
        uni.navigateTo({ url: "/pages2/addr" });
      },
      reLogin() {
        const dig: any = this.$refs.dig;
        if (dig) {
          dig.open({
            confirm: async () => {
              if (this.formData.del) {
                const a = await uni.showModal({ title: "删除警告", content: "是否确认注销当前登录账户?本操作不可恢复!" });
                if (!a.confirm) {
                  return;
                }
              }
              const r = await format.user(await api.request(this.formData, "user/login"));
              if (r) {
                api.me = r;
                api.mid = r.id;
                api.token = r.token;
                gd.addr.splice(0);
                this.init();
              }

            }
          });
        }
      },
      changeDel(e: any) {
        this.formData.del = !e.detail.value;
      }
    },
    beforeUnmount() {
      this.saveData();
    },
  });
</script>
<style lang="scss" scoped>
  .setting {
    position: relative;
    height: 100%;
    background-color: $uni-bg-color-grey;
    .content {
      >.line:first-child {
        font-size: 1.2em;
        color: #333;
        font-weight: 600;
      }
    }
    .line {
      width: 100%;
      margin-top: 1em;
      padding: 0.4em;
      background-color: #fff;
      display: flex;
      >.label {
        width: 6em;
        min-width: 6em;
      }
      >.avatar {
        width: 4em;
        height: 4em;
        border-radius: 50%;
        overflow: hidden;
        image {
          height: 100%;
        }
        >.mac-ico-customer::before {
          font-size: 4em;
          color: $uni-text-color-placeholder;
        }
      }
      >.input {
        pointer-events: none;
      }
      input {
        padding: 0 0.2em;
        border-radius: 0.6em;
        height: auto;
        flex: 1;
      }
    }
  }
  .bottom {
    bottom: 1em;
    width: 100%;
    margin-top: 1.5rem;
    .confirm {
      background-color: $uni-color-primary;
      color: #fff;
      padding: 0.4em 1em;
      border-radius: .2em;
    }
    .switch-user {
      margin-left: 1em;
      background-color: $uni-color-error;
      color: #fff;
      padding: 0.4em 1em;
      border-radius: 0.2em;
    }
  }
  .line-select {
    justify-content: space-between;
    align-items: center;
    .label {
      width: auto !important;
    }
  }
</style>